package uk.co.agileworks.bidpirate.web;

import javax.annotation.Resource;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.Errors;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.SessionAttributes;

import uk.co.agileworks.bidpirate.model.Bid;
import uk.co.agileworks.bidpirate.service.ServiceException;

@Controller
@RequestMapping("/addBid.html")
@SessionAttributes("bid")
public final class AddBidForm extends ControllerHelper {

	static final String FORM = "addBid";
	static final String SUCCESS = "redirect:/listBids.html";

	@Resource
	private Validator<Bid> bidValidator;

	@RequestMapping(method = RequestMethod.GET)
	public void getForm(@ModelAttribute Bid bid, Model model) {
		model.addAttribute(bid);
		model.addAttribute("openItemUrl", getOpenItemUrl());
	}

	@RequestMapping(method = RequestMethod.POST)
	public String postForm(@ModelAttribute("bid") Bid bid, Errors errors) {
		try {
			if (bidValidator.validate(bid, errors)) {
				getBusinessLogic().addBid(bid);
			}
		} catch (ServiceException e) {
			errors.reject(e.getMessage());
		}
		return errors.hasErrors() ? FORM : SUCCESS;
	}
}
